package com.aqielife.demo;

import com.aqelife.webflux.interfaces.ProxyCreator;
import com.aqielife.demo.handler.UserHandler;
import com.aqielife.demo.interfaces.IUserApi;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.nest;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

/**
 * @author aqie
 * @date 2022/03/12 23:04
 * @desc
 */
@Configuration
@EnableMongoRepositories(basePackages = "com.aqielife.demo.repository")
public class MongodbConfig {
    @Bean
    RouterFunction<ServerResponse> userRouter(UserHandler handler) {
        return nest(
                // 相当于类上面的 @RequestMapping("/user")
                path("/user"),
                // 下面的相当于类里面的 @RequestMapping
                // 得到所有用户
                route(GET("/"), handler::getAllUser)
                        // 创建用户
                        .andRoute(POST("/").and(accept(MediaType.APPLICATION_JSON_UTF8)), handler::createUser)
                        // 删除用户
                        .andRoute(DELETE("/{id}"), handler::deleteUserById)
                        .andRoute(GET("/{id}"),handler::findUserById)
        );
    }
    @Bean
    FactoryBean<IUserApi> userApi(ProxyCreator proxyCreator) {      // 参数注入
        return new FactoryBean<IUserApi>() {

            // 返回接口类型
            @Override
            public Class<?> getObjectType() {
                return IUserApi.class;
            }

            /**
             * 返回代理对象
             *  输出 ： 创建的代理类
             */
            @Override
            public IUserApi getObject() throws Exception {
                return (IUserApi) proxyCreator
                        .createProxy(this.getObjectType());
            }
        };
    }
}
